package com.binfenhulian.chinaenergy.ces.manage.core.url2io.executor;

import com.binfenhulian.chinaenergy.ces.manage.core.url2io.bean.enums.ResponseErrorEnum;
import com.binfenhulian.chinaenergy.ces.manage.core.url2io.bean.response.Url2IOResponse;
import com.binfenhulian.chinaenergy.ces.manage.core.url2io.handle.BaseResultHandleThread;
import com.binfenhulian.chinaenergy.ces.manage.core.url2io.processor.BaseExtraProcessor;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanghjbuf on 2018/3/15.
 */
@Slf4j
@Component("com.binfenhulian.chinaenergy.ces.manage.core.url2io.executor.Url2IOExecutor")
public class Url2IOExecutor {

    private int mIndex = 1;
    private int mTotal = 10;
    private Long mSleepTime = 2000L;

    //基础url
    @Value("${url2io.base.url}")
    private String url2ioBaseUrl ;

    /**
     * 针对于特定数据的初始化
     *
     * @param index
     * @param total
     * @param sleepTime
     */
    public void  initUrl2IOExecutor(int index, int total,Long sleepTime ) {
        this.mIndex = index;
        this.mTotal = total;
        this.mSleepTime = sleepTime;
    }

    /**
     * url2io-实际执行逻辑
     *
     * @param beginUrl
     * @param baseExtraProcessor
     * @param baseResultHandleThread
     */
    public List<Url2IOResponse> doExceute(String beginUrl, BaseExtraProcessor baseExtraProcessor, BaseResultHandleThread baseResultHandleThread) {
        StringBuffer sb = null;
        int i = 0;
        List<Url2IOResponse> responses = new ArrayList<>();

        while (i < mTotal) {
            //下一页为空,停止爬取操作
            if(null == beginUrl || "".equals(beginUrl)){
                break;
            }
            sb = new StringBuffer();

            try {
                URL url = new URL(url2ioBaseUrl + beginUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String data;
                while ((data = br.readLine()) != null) {
                    sb.append(data);
                }
                br.close();
                connection.disconnect();
            } catch (MalformedURLException e) {
                log.error("url格式错误,操作失败!", e);
            } catch (IOException e) {
                log.error("IO发生错误,操作失败!", e);
            }

            log.info("url2IOResponse:{};", sb.toString());
            Url2IOResponse url2IOResponse = new Gson().fromJson(sb.toString(), Url2IOResponse.class);
            //错误判断
            if(null != url2IOResponse.getMsg() && null != url2IOResponse.getError()){
                log.info("url2io-msg:{},url2io-error:{};", url2IOResponse.getMsg(), ResponseErrorEnum.getResponseErrorEnumByErrorKey(url2IOResponse.getError()).getErrorRemark());
                if(null == ResponseErrorEnum.getResponseErrorEnumByErrorKey(url2IOResponse.getError())){
                    continue;
                }else{
                    return null;
                }
            }
            url2IOResponse.setTitle(baseExtraProcessor.processTitle(url2IOResponse.getTitle()));
            url2IOResponse.setContent(baseExtraProcessor.processContent(url2IOResponse.getContent()));
            url2IOResponse.setDate(baseExtraProcessor.processDate(url2IOResponse.getDate()));

            //后续处理逻辑
            if (null != baseResultHandleThread) {
                baseResultHandleThread.initBean(url2IOResponse, mIndex);
                baseResultHandleThread.start();
            }

            //更改相关变量
            beginUrl = url2IOResponse.getNext();
            i++;
            mIndex++;
            responses.add(url2IOResponse);

            try {
                Thread.sleep(mSleepTime);
            } catch (InterruptedException e) {
                log.error("线程终端异常发生,操作失败!", e);
            }
        }
        return responses;
    }
}
